//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//

package com.ruoyi.live.product.service;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.live.configuration.SessionInfo;
import com.ruoyi.live.base.domain.LiveProductSource;
import com.ruoyi.live.base.mapper.LiveProductSourceMapper;
import com.ruoyi.live.tool.commons.ICommons;
import com.ruoyi.live.tool.commons.IConvert;
import com.ruoyi.live.tool.utils.Message;
import com.ruoyi.live.tool.utils.PicUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import jakarta.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileOutputStream;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class LiveProductSourceService {
    private static final Logger log = LoggerFactory.getLogger(LiveProductSourceService.class);
    @Autowired
    LiveProductSourceMapper dao;

    public LiveProductSourceService() {
    }

    public void addLiveProductSource(LiveProductSource entity) throws Exception {
        try {
            entity.setCreateTime(System.currentTimeMillis());
            entity.setCreateUser(SessionInfo.getUserId());
            entity.setState(1);
            this.dao.insert(entity);
        } catch (Exception var3) {
            var3.printStackTrace();
            log.error("新增LiveProductSource失败,编号LiveProductSourceService-addLiveProductSource-1");
            throw new Exception("新增失败,编号LiveProductSourceService-addLiveProductSource-1");
        }
    }

    public void updateLiveProductSource(LiveProductSource entity) throws Exception {
        try {
            this.dao.updateById(entity);
        } catch (Exception var3) {
            var3.printStackTrace();
            log.error("更新LiveProductSource失败,编号LiveProductSourceService-updateLiveProductSource-1,id:{}", entity.getId());
            throw new Exception("更新失败,编号LiveProductSourceService-updateLiveProductSource-1");
        }
    }

    public LiveProductSource getLiveProductSource(Long id) {
        return (LiveProductSource)this.dao.selectById(id);
    }

    public int deleteLiveProductSource(String[] ids) throws Exception {
        if (ids.length == 0) {
            throw new Exception("请选择要删除的数据,编号LiveProductSourceService-deleteLiveProductSource-1");
        } else {
            try {
                int count = 0;

                for(int i = 0; i < ids.length; ++i) {
                    if (!ICommons.isNullOrEmpty(ids[i])) {
                        count += this.dao.deleteById(IConvert.string2long(ids[i]));
                    }
                }

                return count;
            } catch (Exception var4) {
                var4.printStackTrace();
                log.error("删除LiveProductSource失败,编号LiveProductSourceService-deleteLiveProductSource-2,ids:{}", ids.toString());
                throw new Exception("删除的数据失败,编号LiveProductSourceService-deleteLiveProductSource-2");
            }
        }
    }

    public List<LiveProductSource> query(LiveProductSource entity) {
        QueryWrapper<LiveProductSource> wrapper = (QueryWrapper)((QueryWrapper)((QueryWrapper)((QueryWrapper)((QueryWrapper)((QueryWrapper)((QueryWrapper)((QueryWrapper)((QueryWrapper)(new QueryWrapper()).eq(!ICommons.isNullOrEmpty(entity.getId()), "id", entity.getId())).eq(!ICommons.isNullOrEmpty(entity.getState()), "state", entity.getState())).eq(!ICommons.isNullOrEmpty(entity.getCreateTime()), "create_time", entity.getCreateTime())).eq(!ICommons.isNullOrEmpty(entity.getCreateUser()), "create_user", entity.getCreateUser())).like(!ICommons.isNullOrEmpty(entity.getSourceName()), "source_name", entity.getSourceName())).like(!ICommons.isNullOrEmpty(entity.getSourceExt()), "source_ext", entity.getSourceExt())).like(!ICommons.isNullOrEmpty(entity.getSourceFolder()), "source_folder", entity.getSourceFolder())).like(!ICommons.isNullOrEmpty(entity.getSourceStoreName()), "source_store_name", entity.getSourceStoreName())).eq(!ICommons.isNullOrEmpty(entity.getProductId()), "product_id", entity.getProductId());
        return this.dao.selectList(wrapper);
    }

    public List<LiveProductSource> getImages(Long id, Integer type) {
        return this.dao.selectList((Wrapper)(new QueryWrapper((new LiveProductSource()).setSourceType(type).setProductId(id))).orderByDesc("create_time"));
    }

    public Message upload(Long id, Integer type, Integer section, HttpServletRequest request) {
        Integer count = 0;
        String result = "";
        List<MultipartFile> files = ((MultipartHttpServletRequest)request).getFiles("file");
        Iterator var8 = files.iterator();

        while(var8.hasNext()) {
            MultipartFile file = (MultipartFile)var8.next();

            try {
                this.doUpload(file, id, type, section, request);
                count = count + 1;
            } catch (Exception var12) {
                var12.printStackTrace();
                result = result + "失败原因：" + var12.getMessage();
            }
        }

        int allCount = files.size();
        return count == allCount ? new Message(true, "上传成功") : new Message(true, result);
    }

    private void doUpload(MultipartFile file, Long id, Integer type, Integer section, HttpServletRequest request) throws Exception {
        String fileName = file.getOriginalFilename();
        if (ICommons.isNullOrEmpty(fileName)) {
            throw new Exception("文件名不能为空");
        } else {
            if (fileName.indexOf("\\") != -1) {
                fileName = fileName.substring(fileName.lastIndexOf("\\"));
            }

            String ext = fileName.substring(fileName.lastIndexOf(".")).toLowerCase();
            if (ICommons.isNullOrEmpty(ext)) {
                throw new Exception("扩展名不能为空");
            } else if (!".jpg.png.bmp.jpeg.gif".contains(ext)) {
                throw new Exception("请上传.jpg.png.bmp.jpeg.gif文件");
            } else {
                String filePath = request.getServletContext().getRealPath("/static/static/data/" + id + "/" + type + "/");
                File targetFile = new File(filePath);
                if (!targetFile.exists()) {
                    targetFile.mkdirs();
                }

                FileOutputStream out = null;
                String name = UUID.randomUUID().toString().replaceAll("-", "") + ext;

                try {
                    out = new FileOutputStream(filePath + name);
                    out.write(file.getBytes());
                } catch (Exception var22) {
                    var22.printStackTrace();
                    throw new Exception("上传失败");
                } finally {
                    try {
                        out.flush();
                        out.close();
                    } catch (Exception var20) {
                        var20.printStackTrace();
                    }

                }

                Map size = PicUtils.getImgSize(filePath + name);

                try {
                    LiveProductSource ps = (new LiveProductSource()).setCreateTime(System.currentTimeMillis()).setCreateUser(SessionInfo.getUserId()).setState(1).setProductId(id).setSourceExt(ext).setSourceType(type).setSourceName(fileName).setSourceStoreName(name).setWidth((Integer)size.get("width")).setHeight((Integer)size.get("height")).setAnswer(2).setFirst(2).setSection(section);
                    this.dao.insert(ps);
                } catch (Exception var21) {
                    var21.printStackTrace();
                    throw new Exception("上传数据保存失败");
                }
            }
        }
    }

    public List<LiveProductSource> getSources(Integer type, Long productId) {
        return this.dao.selectList((Wrapper)(new QueryWrapper((new LiveProductSource()).setProductId(productId).setSourceType(type))).orderByDesc("create_time"));
    }

    @CacheEvict(
            value = {"getProductSourceByProductId", "getAllSourceByProductId"},
            key = "#entity.id"
    )
    public void picSetting(LiveProductSource entity) {
        this.dao.updateById(entity);
    }

    public List<List<LiveProductSource>> getContentSources(Long productId) {
        List<LiveProductSource> list = this.dao.selectList((Wrapper)(new QueryWrapper((new LiveProductSource()).setProductId(productId).setSourceType(2))).orderByDesc("create_time"));
        Map<Integer, List<LiveProductSource>> res = new HashMap();
        res.put(1, new ArrayList());
        res.put(2, new ArrayList());
        res.put(3, new ArrayList());
        res.put(4, new ArrayList());
        res.put(5, new ArrayList());
        res.put(6, new ArrayList());
        Iterator var4 = list.iterator();

        while(var4.hasNext()) {
            LiveProductSource source = (LiveProductSource)var4.next();
            ((List)res.get(source.getSection())).add(source);
        }

        return (List)res.entrySet().stream().map((e) -> {
            return (List)e.getValue();
        }).collect(Collectors.toList());
    }

    @CacheEvict(
            value = {"getProductSourceByProductId", "getAllSourceByProductId"},
            key = "#id"
    )
    public void setSection(Long id, Integer section) {
        this.dao.updateById((new LiveProductSource()).setId(id).setSection(section));
    }
}
